package top.asteam.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.asteam.entity.Payment;
import top.asteam.exception.BusinessException;
import top.asteam.service.IPaymentService;
import top.asteam.entity.CommonResult;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author Rock Wang
 * @Time 2021/4/10
 */
@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private IPaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/lb")
    public String lb() {
        return serverPort;
    }

    @GetMapping("/getById")
    public CommonResult getById(@RequestParam Long id) {
        Payment byId = paymentService.getById(id);
        return CommonResult.OkData(byId).setMessage("查询成功, port: " + serverPort);
    }

    @PostMapping("/save")
    public CommonResult create(@RequestBody @Validated Payment payment) {
        boolean save = paymentService.save(payment);
        if (save) {
            return CommonResult.Ok().setMessage("insert ok , port: " + serverPort);
        } else {
            throw new BusinessException(101, "插入失败");
        }
    }

    @GetMapping("/getAll")
    public CommonResult getAll() {
        List<Payment> list = paymentService.list();
        return CommonResult.OkData(list).setMessage("找到啦, port: " + serverPort);
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();

        services.forEach(service -> {
            log.info("discovery service :" + service);
        });

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        instances.forEach(serviceInstance -> {
            log.info(serviceInstance.getServiceId() + "\t" + serviceInstance.getHost() + "\t" + serviceInstance.getPort() + "\t" + serviceInstance.getUri());
        });

        return this.discoveryClient;
    }

    @GetMapping("/timeout")
    public String PaymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return serverPort;
    }

}
